package cn.walnut.controller;

import cn.walnut.domain.User;
import cn.walnut.domain.UserQueryCondition;
import com.fasterxml.jackson.annotation.JsonView;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @program: walnut-security
 * @Date: 2018/12/18 0:30
 * @Author: Walnut1992
 * @Description:
 */
@RestController
@RequestMapping(value = "/user")
public class UserController {

    /**
     * 列表显示
     * @param userQueryCondition
     * @return
     */
    @GetMapping
    @JsonView(User.UserSimpleView.class)
    @ApiOperation(value = "用户查询功能")
    public List<User> queryUser(UserQueryCondition userQueryCondition) {
        List<User> users = new ArrayList<>();
        users.add(new User());
        users.add(new User());
        users.add(new User());
        return users;
    }

    /**
     * 查看详情
     * @param id
     * @return
     */
    @GetMapping(value = "/{id:\\d+}")
    @ApiOperation(value = "查看用户详情")
    public User getInfo(@ApiParam("用户id") @PathVariable(value = "id") String id) {
        //throw new UserNotExistException(id);
        User user = new User();
        user.setUsername("tome");
        user.setId("1222");
        user.setBirthday(new Date());
        return user;
    }

    /**
     * 新增
     * @param user
     * @param errors
     * @return
     */
    @PostMapping
    public User saveUser(@Valid @RequestBody User user, BindingResult errors) {
        if(errors.hasErrors()) {
            errors.getAllErrors().stream().forEach(error -> System.out.println(error.getDefaultMessage()));
        }
        user.setUsername(user.getUsername());
        user.setPassword(user.getPassword());
        user.setBirthday(user.getBirthday());
        return user;
    }

    /**
     * 删除
     * @param id
     */
    @DeleteMapping(value = "/{id}")
    public void delete(@PathVariable("id") String id) {
        System.out.println(id);
    }

    /**
     * 修改
     * @param id
     * @param user
     * @return
     */
    @PutMapping(value = "{id:\\d+}")
    public User update(@PathVariable("id") String id,@Valid @RequestBody User user,BindingResult errors) {
        if(errors.hasErrors())
            errors.getAllErrors().stream().forEach(error -> {
                System.out.println(error.getObjectName() + "+++++++++++++++++++++");
                System.out.println(error.getDefaultMessage() + "+++++++++++++++++++++");
            });
        return user;
    }
}
